package services

import (
	"fmt"
	"user/config"
	"user/model"
)

func GetUser(id int64) *model.User {
	sql := `
	select id,name,addr,sex from user4 where id =?
	`
	var (
		ids  int64
		name string
		addr string
		sex  bool
	)

	row := config.Db.QueryRow(sql, id)
	row.Scan(&ids, &name, &addr, &sex)
	return &model.User{ids, name, sex, addr}
}

func GetUsers() *[]model.User {
	users := make([]model.User, 0)
	sql := `
	select id,name,addr,sex from user4
	`
	rows, err := config.Db.Query(sql)
	if err != nil {
		fmt.Println(err)
		return nil
	}

	for rows.Next() {
		var (
			id   int64
			name string
			addr string
			sex  bool
		)
		rows.Scan(&id, &name, &addr, &sex)
		users = append(users, *model.NewUser(id, name, addr, sex))
		// fmt.Println(id, name, addr, sex)
	}
	return &users
}

func AddUser(name, addr string, sex bool) {
	sql := `
	insert into user4(name,addr,sex,created_at,updated_at) values (?,?,?,now(),now());
	`
	// fmt.Println(name, addr, sex)
	result, err := config.Db.Exec(sql, name, addr, sex)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(result.RowsAffected())
}

func EditUser(id int64, name, addr string, sex bool) {
	sql := `
	update user4 set name=?,addr=?,sex=? where id=? 
	`
	result, err := config.Db.Exec(sql, name, addr, sex, id)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(result.RowsAffected())
}

func DelUser(id int64) {
	sql := `
	delete from user4 where id = ?
	`
	result, err := config.Db.Exec(sql, id)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(result.RowsAffected())

}
